#include "mywifi_manager.h"
#include <WiFiClientSecure.h>

#define LED_BUILTIN1 2
#define LED_BUILTIN2 0

const char *host = "frp-bus.top"; // 不需要加 https://
const uint16_t port = 64971;
WiFiClientSecure client;
String get_new_state = "";
String post_current_state = "";
String macStr = "";

void getMAC_make_url()
{
  byte mac[6];
  WiFi.macAddress(mac); // 获取MAC地址
  String macStr = "";
  for (int i = 0; i < 6; i++)
  {
    macStr += String(mac[i], HEX); // 将每个字节转换为十六进制字符串
    if (i < 5)
    { // 在每个字节后（除了最后一个字节）添加冒号
      macStr += ":";
    }
  }
  int buttonState = digitalRead(LED_BUILTIN1);

  // 构造GET和POST请求
  get_new_state = String("GET /LEDcontrol/") + macStr + " HTTP/1.1\r\n" +
                  "Host: " + String(host) + ":" + String(port) + "\r\n" +
                  // "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0\r\n" +
                  // "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8\r\n" +
                  // "Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\r\n" +
                  // "Accept-Encoding: gzip, deflate, br, zstd\r\n" +
                  // "Referer: https://" + String(host) + ":" + String(port) + "/LED/" + macStr + "\r\n" +
                  "Connection: keep-alive\r\n\r\n";

  int contentLength = String("buttonState=" + String(buttonState)).length();
  post_current_state = String("POST /LEDcontrol/") + macStr + " HTTP/1.1\r\n" +
                       "Host: " + String(host) + ":" + String(port) + "\r\n" +
                      //  "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8\r\n" +
                       "Content-Type: application/x-www-form-urlencoded\r\n" +
                       "Content-Length: " + String(contentLength) + "\r\n" +
                      //  "Origin: https://" + String(host) + ":" + String(port) + "\r\n" +
                      //  "Referer: https://" + String(host) + ":" + String(port) + "/LED/" + macStr + "\r\n" +
                       "Connection: keep-alive\r\n\r\n" +
                       "buttonState=" + String(buttonState);
}

void setup()
{
  Serial.begin(9600);
  pinMode(LED_BUILTIN1, OUTPUT);
  pinMode(LED_BUILTIN2, OUTPUT);
  setupWiFi();
  client.setInsecure(); // 跳过证书验证

  // 连接到服务器
  while (!client.connect(host, port))
  {
    Serial.println("未连接到网址，重试中。。。");
    delay(1000);
  }
  Serial.println("已连接到网站");
}

void request()
{
  getMAC_make_url();

  // 发送POST请求上传当前引脚状态
  client.print(post_current_state);

  // 等待服务器响应
  String response = "";
  while (client.connected() || client.available())
  {
    if (client.find("HTTP/1.1 302 Found"))
    {
      Serial.println("POST请求处理成功，重定向到其他页面，停止处理。");
      break; // 停止处理，退出请求
    }
    else
    {
      Serial.println("POST请求失败");
      break; // 处理失败，退出请求
    }
  }
  delay(500);
  // 如果不是重定向，则发送GET请求
  client.print(get_new_state);

  // 处理GET请求响应
  while (client.connected() || client.available())
  {
    if (client.find("buttonState:"))
    {
      bool buttonState = client.readStringUntil('\n').toInt();
      Serial.print("buttonState: ");
      Serial.println(buttonState);
      digitalWrite(LED_BUILTIN1, buttonState == 0 ? LOW : HIGH);
    }
  }

  if (client.connected())
  {
    Serial.println("连接正常，退出函数。");
    return; // 直接退出
  }
  else
  {
    Serial.println("连接已断开，准备重新连接...");
    if (client.connect(host, port))
    {
      Serial.println("已重新连接到网站");
    }
    else
    {
      Serial.println("重新连接失败，稍后再试。");
    }
  }
}

void loop()
{
  request();
  delay(1000); // 适当的延迟
}
